package com.imufe.chemicalenterprisedangerwarning.security;

import com.alibaba.fastjson.JSON;
import com.imufe.chemicalenterprisedangerwarning.common.InfoCode;
import com.imufe.chemicalenterprisedangerwarning.common.ResponseEntity;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 没有权限 处理器
 * @author BaiBan
 * @since 2022/10/15
 */
@Component
public class CustomizeAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException {
        ResponseEntity<Object> result = ResponseEntity.fail(InfoCode.USER_NO_PERMISSION);
        //处理编码方式，防止中文乱码的情况
        httpServletResponse.setContentType("text/json;charset=utf-8");
        // 把Json数据放到HttpServletResponse中返回给前台
        httpServletResponse.getWriter().write(JSON.toJSONString(result));
    }
}